package com.esb.rpc.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.esb.transport.channel.Channel;
import com.esb.transport.protocal.Request;
import com.esb.transport.protocal.Response;

public class InvokerInvocationHandler implements InvocationHandler {
	private final Channel channel;

	public InvokerInvocationHandler(Channel channel) {
		this.channel = channel;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		String methodName = method.getName();
		Class<?>[] parameterTypes = method.getParameterTypes();
		if (method.getDeclaringClass() == Object.class) {
			return method.invoke(proxy, args);
		}
		if ("toString".equals(methodName) && parameterTypes.length == 0) {
			return proxy.toString();
		}
		if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
			return proxy.hashCode();
		}
		if ("equals".equals(methodName) && parameterTypes.length == 1) {
			return proxy.equals(args[0]);
		}
		Response res = channel.send(new Request(0L, method, args)).get();
		if(res==null)return null;
 		return res.getResult();
	}
}
